import config from "../conf/Config.js";
import OSS from 'ali-oss';
import {
	pathToBase64,
	base64ToPath
} from 'image-tools';

import localStore from "../LocalStore.js";
import util from "../util/Util.js";
import staticConst from "../const/StaticConst.js";
import goodsCtrl from "../gd/GoodsCtrl.js";
import projectCtrl from "../project/GoodsCtrl.js";


import cmd from "../Cmd.js";

import lang from "../conf/Lang.js";


import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
let self = Vue.prototype;

const IMAGE_PNG = 'image/png';
var uploadPic = {
	imgList: [],
	callBack: null,
	tempImgUlr: "",
	sgin: null,
	type: -1,
	uploadSussecc: null,
	index: -1,
	parentIdx: -1,
	tabId: -1,
	is_good: '',
	itemId: -1,
	batchid: -1,
	idyun: -1,
	activeId: -1,
};

uploadPic.chooseImage1 = function (callBack) {
	let that = this;
	this.callBack = callBack;
	uni.chooseImage({
		count: 1,
		sizeType: ['original'],
		success: (res) => {
			console.log("选择文件==:", res);
			that.tempImgUlr = res.tempFilePaths[0];
			let canvas2 = document.createElement("canvas");
			let ctx = canvas2.getContext("2d");
			let img = new Image();
			img.src = res.tempFilePaths[0];
			img.onload = () => {
				if (img.complete) {
					let w = img.width;
					let h = img.height;
					let obj = {};
					obj.url = res.tempFilePaths[0];
					if (that.callBack) {
						that.callBack(obj);
						ctx.restore();
						img.src = "";
						img = null;
						that.callBack = null;
						that.creatCanvas1(obj.url);
					}
				}
			}
		},

		fail: (err) => {

		}
	})
}

uploadPic.creatCanvas1 = function (data) {
	uni.showLoading({
		title: lang.uploadPicTxt.upLoadTxt,
		mask: true,
	})
	let blob = data;
	pathToBase64(blob) //上传原图
		.then(base64 => {
			blob = this.dataURLtoBlob(base64);
			this.getSgin1(blob);
		})
		.catch(error => {
			console.error(error);
			uni.hideLoading();
		});
}

uploadPic.getSgin1 = async function (blob) {
	let that = this;
	let url = config.UPLOAD_IMG_KEY;
	let param = {};
	param.act = "oss";
	let res = await self.$api({
		url: url,
		data: param,
		showLoading: false
	});

	if (res == null || res.status != 1) return;
	console.log("res==:", res);
	if (res.status == 1) {
		that.sgin = res.data;
		let client = new OSS({
			accessKeyId: that.sgin.AccessKeyId,
			accessKeySecret: that.sgin.AccessKeySecret,
			stsToken: that.sgin.SecurityToken,
			region: that.sgin.oss.regionid,
			bucket: that.sgin.oss.bucket,
			endpoint: that.sgin.oss.endpoint, //自定义域名必传
			cname: true, //自定义域名必传
		});
		that.putBlob1(client, blob);
	} else {
		uni.hideLoading();
	}
}

//上传OSS
uploadPic.putBlob1 = async function (client, blob) {
	try {
		let cp = await localStore.getCpInfo();
		let p = staticConst.getPath(this.type, cp.id, this.idyun, this.activeId);
		let fn = util.getJpgFileName();
		let fileName = p + fn;
		console.log('路径', p);
		let result = await client.put(fileName, blob);
		if (result) {
			// self.$msg({title:'上传图片成功！',mask:true});
			self.$msg({
				title: '上传图片成功！'
			});
			if (this.uploadSussecc) {
				console.log("result=======:",result);
				this.uploadSussecc(result);
				this.uploadSussecc = null;
			}
		} else {
			self.$msg({
				title: '上传图片失败！'
			});
		}
	} catch (e) {

		console.log("上传图片失败!!=====:",JSON.stringify(e));
		self.$msg({
			title: '上传图片失败!!'
		});
	}
	uni.hideLoading();
}



/***选择图片***/
uploadPic.chooseImage = function (callBack, type, index, parentIdx, tabId, is_good, itemId, batchid, idyun, activeId) {
	let that = this;
	this.type = type;
	this.is_good = is_good
	this.callBack = callBack;
	this.index = index;
	this.parentIdx = parentIdx;
	this.tabId = tabId;
	this.itemId = itemId;
	this.batchid = batchid
	this.idyun = idyun
	this.activeId = activeId
	console.log("batchid=============>", this.batchid);

	uni.chooseImage({
		count: 1,
		sizeType: ['original'],

		success: (res) => {
			console.log("选择文件==:", res);
			that.tempImgUlr = res.tempFilePaths[0];
			let canvas2 = document.createElement("canvas");
			let ctx = canvas2.getContext("2d");
			let img = new Image();
			img.src = res.tempFilePaths[0];
			img.onload = () => {
				if (img.complete) {
					let w = img.width;
					let h = img.height;
					let obj = {};
					obj.w = img.width;
					obj.h = img.height;
					obj.index = index;
					obj.parentIdx = parentIdx;
					obj.itemId = itemId;
					obj.tabId = tabId;
					obj.url = res.tempFilePaths[0];
					obj.type = type; //区分编辑，头像，产品，或是产品详情图片
					if (that.callBack) {
						that.callBack(obj);
						ctx.restore();
						img.src = "";
						img = null;
						that.callBack = null;
					}
				}
			}
		},

		fail: (err) => {

		}
	})
}

uploadPic.creatCanvas = function (data, original, successBack = null) {
	uni.showLoading({
		title: lang.uploadPicTxt.upLoadTxt,
		mask: true,
	})
	let blob = data;
	this.uploadSussecc = successBack;
	if (!original) {
		blob = this.dataURLtoBlob(data); //上传切割图
		this.getSgin(blob);
	} else {
		pathToBase64(blob) //上传原图
			.then(base64 => {
				blob = this.dataURLtoBlob(base64);
				this.getSgin(blob);
			})
			.catch(error => {
				console.error(error);
				uni.hideLoading();
			})
	}

}

uploadPic.getSgin = async function (blob, original) {
	let that = this;
	let url = config.UPLOAD_IMG_KEY;
	let param = {};
	param.act = "oss";
	let res = await self.$api({
		url: url,
		data: param,
		showLoading: false
	});

	if (res == null || res.status != 1) return;
	console.log("res==:", res);
	if (res.status == 1) {
		that.sgin = res.data;
		let client = new OSS({
			accessKeyId: that.sgin.AccessKeyId,
			accessKeySecret: that.sgin.AccessKeySecret,
			stsToken: that.sgin.SecurityToken,
			region: that.sgin.oss.regionid,
			bucket: that.sgin.oss.bucket,
			endpoint: that.sgin.oss.endpoint, //自定义域名必传
			cname: true, //自定义域名必传
		});
		that.putBlob(client, blob, original);
	} else {
		uni.hideLoading();
	}
}

//base64转blob
uploadPic.dataURLtoBlob = function (dataurl) {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}

//将blob转换为file
uploadPic.blobToFile = function (theBlob, fileName) {
	theBlob.lastModifiedDate = new Date();
	theBlob.name = fileName;
	return theBlob;
}

// 调用方法转换图片
uploadPic.getpictuer = function (dataUrl) {
		var _blob = this.dataURLtoBlob(dataUrl);
		var suffix = dataUrl.split(';')[0].split(':')[1].split('/')[1]; //文件扩展名
		var _filename = String(new Date().getTime()) + '.' + suffix;
		var _file = this.blobToFile(_blob, filename)
		var fileObj = {};
		fileObj.file = _file;
		fileObj.filename = _file.name;
		return fileObj;
	},

	//上传OSS
	uploadPic.putBlob = async function (client, blob) {
		try {
			let cp = await localStore.getCpInfo();
			let p = staticConst.getPath(this.type, cp.id, this.idyun, this.activeId);
			let fn = util.getJpgFileName();
			let fileName = p + fn;
			console.log('路径', p);

			console.log("client============:", client);

			let result = await client.put(fileName, blob);
			if (result) {
				// self.$msg({title:'上传图片成功！',mask:true});
				self.$msg({
					title: '上传图片成功！'
				});
				console.log("图片结果==：", result);
				if (this.type == staticConst.UPLOAD_GOODS) {
					console.log(this.index);
					if (this.is_good == 1) {
						goodsCtrl.uploadGdsPhoto(this.index, result); //上传产品列表图片

					} else {
						projectCtrl.uploadGdsPhoto(this.index, result); //上传产品列表图片

					}

				} else if (this.type == staticConst.UPLOAD_OTHER) {
					let data = {};
					data.tabId = this.tabId;
					data.parentIdx = this.parentIdx;
					data.index = this.index;
					data.name = result.name;
					data.url = result.url;
					data.itemId = this.itemId
					if (this.is_good == 1) {
						goodsCtrl.uploadGdsMoreDetailPhoto(data);
					} else {
						projectCtrl.uploadGdsMoreDetailPhoto(data);
					}



				} else if (this.type == staticConst.UPLOAD_REMASK ||
					this.type == staticConst.UPLOAD_AVATAR ||
					this.type == staticConst.UPLOAD_ORDER_REMASK ||
					this.type == staticConst.UPLOAD_INTER_ACTIVE) {
					if (this.uploadSussecc) {
						this.uploadSussecc(this.index, result.name, result, this.batchid);
					}
				}
			} else {
				self.$msg({
					title: '上传图片失败！'
				});
			}
		} catch (e) {

			console.log(JSON.stringify(e));
			self.$msg({
				title: '上传图片失败!!'
			});
		}
		uni.hideLoading();
	}

export default uploadPic;